import {Component, Input, OnInit, Output, EventEmitter} from '@angular/core';
import {AlertService} from '../alert.service';
import {LoadingService} from '../loading.service';
import {Http} from '@angular/http';

@Component({
  selector: 'app-address-selection',
  templateUrl: './address-selection.component.html',
  styleUrls: ['./address-selection.component.scss']
})
export class AddressSelectionComponent implements OnInit {
    // 是否需要乡镇
    @Input() needTowns: Boolean = false;
    // 如需已有省市县，需要获取
    @Input() getprovinceName: any;
    @Input() getdistrictName: any;
    @Input() getcountyName: any;
    @Input() gettownshipName: any;
    // 省市县是否能选择
    @Input() disabled: Boolean = false;
    // 输出省市县乡
    @Output() provinceName: EventEmitter<any> = new EventEmitter();
    @Output() districtName: EventEmitter<any> = new EventEmitter();
    @Output() countyName: EventEmitter<any> = new EventEmitter();
    @Output() townshipName: EventEmitter<any> = new EventEmitter();

    // 保存省市县乡四级城市数据
    public provinceData: Array<any> = [];
    public districtData: Array<any> = [];
    public countyData: Array<any> = [];
    public townshipData: Array<any> = [];
    public provinceString: any;
    public districtString: any;
    public countyString: any;
    public townshipString: any;
    // public provinceName: string;
    // public districtName: string;
    // public countyName: string;
    // public townshipName: string;
  constructor(
      public alert: AlertService,
      public loading: LoadingService,
      public http: Http,
  ) { }

    ngOnInit() {
        const CityData = [];
        this.http.get('http://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key=1be2a14104ac5734e58faf4984c85193').subscribe(
            data => {
                data = data.json();
                const allProvince = data['districts'][0]['districts'];
                allProvince.forEach((value, index) => {
                    const tempData = {'name': value.name, 'code': value.adcode, 'children': []};
                    if (value.name === '台湾省') {
                        tempData.children.push({'name': '台湾', 'code': value.adcode, 'children': []});
                        tempData.children[0]['children'].push({'name': '', 'code': value.adcode});
                    } else {
                        value.districts.forEach((value2, index2) => {
                            tempData.children.push({'name': value2.name, 'code': value2.adcode, 'children': []});
                            if (value2.districts.length === 0) {
                                tempData.children[index2]['children'].push({'name': '', 'code': value2.adcode});
                            } else {
                                value2.districts.forEach((value3, index3) => {
                                    tempData.children[index2]['children'].push({'name': value3.name, 'code': value3.adcode});
                                });
                            }
                        });
                    }
                    if (value.name === '河南省') {
                        value.districts.forEach((value2, index2) => {
                            if (value2.name === '济源市') {
                                tempData.children[index2]['children'] = [];
                                tempData.children[index2]['children'].push({'name': value2.name, 'code': value2.adcode});

                            }
                        });
                    }
                    CityData.push(tempData);
                });
                this.provinceData = CityData;
                this.provinceString = '';
                this.districtString = '';
                this.countyString = '';
                this.townshipString = '';
                if (this.getprovinceName) {
                    for (let i = 0; i < this.provinceData.length; i++) {
                        if (this.getprovinceName === this.provinceData[i]['name']) {
                            this.provinceString = i;
                            this.districtData = this.provinceData[i]['children'];
                            for (let j = 0; j < this.districtData.length ; j++) {
                                if (this.getdistrictName === this.districtData[j]['name']) {
                                    this.districtString = j ;
                                    this.countyData = this.districtData[j]['children'];
                                    for (let k = 0; k < this.countyData.length ; k++) {
                                        if (this.getcountyName === this.countyData[k]['name']) {
                                            this.countyString = this.countyData[k]['code'];
                                            if (this.needTowns) {
                                                this.http.get('http://restapi.amap.com/v3/config/district?keywords=' + this.countyString + '&subdistrict=3&key=9b9e0d616788c62f65f6749a81d2077d').subscribe(
                                                    datas => {
                                                        datas = datas.json();
                                                        this.townshipData = datas['districts'][0]['districts'];
                                                        for ( let a = 0; a < this.townshipData.length ; a++) {
                                                            if (this.gettownshipName === this.townshipData[a]['name']) {
                                                                this.townshipString = a;
                                                            }
                                                        }
                                                        this.loading.hide()
                                                    },
                                                    error => {
                                                        this.alert.hide();
                                                        this.alert.show('系统繁忙');
                                                    }
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        );
    }
// 选择省份获取市级数据
    getcityData() {
        if (this.provinceString === '') {
            this.districtData = [];
            this.countyData = [];
            this.townshipData = [];
            this.districtString = '';
            this.countyString = '';
            this.townshipString = '';
            this.provinceName.emit('');
            this.districtName.emit('');
            this.countyName.emit('');
            this.townshipName.emit('');
        } else {
            this.loading.show();
            this.districtData = [];
            this.countyData = [];
            this.townshipData = [];
            this.districtString = '';
            this.countyString = '';
            this.townshipString = '';
            this.provinceName.emit('');
            this.districtName.emit('');
            this.countyName.emit('');
            this.townshipName.emit('');
            this.provinceName.emit(this.provinceData[parseInt(this.provinceString)]['name']);
            this.districtData = this.provinceData[parseInt(this.provinceString)]['children'];
            this.loading.hide();
        }
    }

    // 选择市级获取县级数据
    getcountyData() {
        if (this.districtString === '') {
            this.countyData = [];
            this.townshipData = [];
            this.countyString = '';
            this.townshipString = '';
            this.districtName.emit('');
            this.countyName.emit('');
            this.townshipName.emit('');
        } else {
            this.loading.show();
            this.countyData = [];
            this.townshipData = [];
            this.countyString = '';
            this.townshipString = '';
            this.districtName.emit('');
            this.countyName.emit('');
            this.townshipName.emit('');
            this.districtName.emit(this.districtData[parseInt(this.districtString)]['name']);
            this.countyData = this.districtData[parseInt(this.districtString)]['children'];
            this.loading.hide();
        }
    }

    gettownshipdata() {
        if (this.countyString === '') {
            this.townshipData = [];
            this.townshipString = '';
            this.countyName.emit('');
            this.townshipName.emit('');
        } else {
            for (let i = 0; i < this.countyData.length; i++) {
                if (this.countyData[i]['code'] === this.countyString) {
                    this.countyName.emit(this.countyData[i]['name']);
                }
            }
            if (this.needTowns) {
                this.loading.show();
                this.http.get('http://restapi.amap.com/v3/config/district?keywords=' + this.countyString + '&subdistrict=3&key=9b9e0d616788c62f65f6749a81d2077d').subscribe(
                    res => {
                        res = res.json();

                        this.townshipData = [];
                        this.townshipString = '';
                        this.townshipName.emit('');
                        this.townshipData = res['districts'][0]['districts'];
                        this.loading.hide()
                    },
                    error => {
                        this.alert.hide();
                        this.alert.show('系统繁忙');
                    }
                );
            }
        }
    }

    // 获取乡镇
    ownship() {
        if (this.townshipString === '') {
            this.townshipName.emit('');
        } else {
            this.townshipName.emit(this.townshipData[this.townshipString]['name']);
        }
    }
}
